package com.gzw.shop.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.gzw.shop.App;
import com.gzw.shop.Contans;
import com.gzw.shop.R;
import com.gzw.shop.adapter.AddressAdapter;
import com.gzw.shop.bean.Address;
import com.gzw.shop.http.OkHttpHelper;
import com.gzw.shop.http.SpotsCallBack;
import com.gzw.shop.msg.BaseRespMsg;
import com.gzw.shop.widget.GToolbar;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Response;

public class AddressListActivity extends BaseActivity implements AddressAdapter.AddressListener {

    private final int REQUEST_CODE = 100;

    private AddressAdapter adapter;

    private boolean isOrder = false;//是否从订单页面过来

    @BindView(R.id.toolbar)
    GToolbar toolbar;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    public List<Address> datas;

    private Intent intent;
    private Address address;

    public OkHttpHelper helper = OkHttpHelper.getInstance();

    @Override
    public int getLayoutId() {
        return R.layout.activity_address_list;
    }

    @Override
    public void initView() {

        toolbar.setRightBtnOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddressListActivity.this, AddressAddActivity.class);
                startActivityForResult(intent, true, REQUEST_CODE);
            }
        });

        toolbar.setIvLeftOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (isOrder) {

                    if (address != null) {
                        intent.putExtra("address", address);
                    }
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    finish();
                }
            }
        });

        intent = getIntent();

        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            isOrder = bundle.getBoolean("order");
        }


    }

    @Override
    public void initData() {

        datas = new ArrayList<>();
        initAddress();
    }

    private void initAddress() {

        Map<String, Object> params = new HashMap<>(1);
        params.put("user_id", App.getInstance().getUser().getId());

        helper.get(Contans.API.ADDRESS_LIST, params, new SpotsCallBack<List<Address>>(this) {
            @Override
            public void onSuccess(Response response, List<Address> datas) {
                showAddress(datas);

                for (Address addr : datas) {
                    if (addr.getIsDefault()) {
                        address = addr;
                    }
                }

            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }

    private void showAddress(List<Address> datas) {

        this.datas.clear();
        this.datas.addAll(datas);

        //进行排序
        Collections.sort(this.datas);

        if (adapter == null) {
            adapter = new AddressAdapter(this, this.datas, this);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            if (RESULT_OK == resultCode) {
                initAddress();
            }
        }
    }

    @Override
    public void setDefault(Address address, boolean isDefault) {

        updateAddress(address, isDefault);
    }

    @Override
    public void deleteAddress(final long id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("你确定要删除该地址吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                delAddress(id);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    public void editAddress(Address address) {
        Intent intent = new Intent(this, AddressAddActivity.class);
        intent.putExtra("address", address);
        startActivityForResult(intent, REQUEST_CODE);
    }

    private void delAddress(long id) {

        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        helper.post(Contans.API.ADDRESS_DEL, params, new SpotsCallBack<BaseRespMsg>(this) {
            @Override
            public void onSuccess(Response response, BaseRespMsg msg) {
                if (msg.getStatus() == BaseRespMsg.STATUS_SUCCESS) {
                    initAddress();
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {
            }
        });
    }

    private void updateAddress(Address address, boolean isDefault) {

        Map<String, Object> params = new HashMap<>();
        params.put("id", address.getId());
        params.put("consignee", address.getConsignee());
        params.put("phone", address.getPhone());
        params.put("addr", address.getAddr());
        params.put("zip_code", address.getZipCode());
        params.put("is_default", isDefault);

        helper.post(Contans.API.ADDRESS_UPDATE, params, new SpotsCallBack<BaseRespMsg>(this) {
            @Override
            public void onSuccess(Response response, BaseRespMsg msg) {

                if (msg.getStatus() == BaseRespMsg.STATUS_SUCCESS) {
                    initAddress();
                }
            }

            @Override
            public void onError(Response response, int code, Exception e) {

            }
        });
    }
}
